import React from 'react';
import cx from 'classnames';

import { pageBack } from '@packages/lib-history';
import os from '@packages/lib-os';

import { onTouchEnd } from '../../global';
import { POPUP_WINDOW, TOP_NAV_HEIGHT } from '../../heightChangeFit';

import S from './index.m.less';

import showHide from '@wpt/showHide';

const onTap = onTouchEnd;

export function shouldRenderNavigation() {
    return (os.isFullscreen && POPUP_WINDOW) || WPT.os.forceShowNavigation;
}

export function back() {
    pageBack();
}

export function close() {
    WPT.wptBridge.closeWebView();
}

const themeConfig = {
    default: {
        backgroundColor: '#FFFFFF',
        textColor: '#333',
        operationIconTheme: 'dark',
        statusBarTheme: 'dark',
        leftBtn: undefined,
        leftBtnShow: true,
        rightBtn: undefined,
        rightBtnTheme: 'more',
        rightBtnShow: true,
        closeBtnShow: true,
        needNavigation: true,
        customNavigation: undefined,
        customTitle: '',
    },
    red: {
        backgroundColor: '#A02731',
        textColor: '#FFFFFF',
        operationIconTheme: 'light',
        statusBarTheme: 'light',
        leftBtn: undefined,
        leftBtnShow: true,
        rightBtn: undefined,
        rightBtnShow: true,
        rightBtnTheme: 'more',
        closeBtnShow: true,
        needNavigation: true,
        customNavigation: undefined,
        customTitle: '',
    },
    scroll: {
        backgroundColor: 'rgba(1, 1, 1, 0)',
        textColor: 'rgba(1, 1, 1, 0)',
        operationIconTheme: 'light',
        statusBarTheme: 'light',
        leftBtn: undefined,
        leftBtnShow: true,
        rightBtn: undefined,
        rightBtnShow: true,
        rightBtnTheme: 'more',
        closeBtnShow: false,
        needNavigation: true,
        customNavigation: undefined,
        customTitle: '',
    },
};

const isBlack = {
    dark: 1,
    light: 0,
};

function addNewStyle(newStyle) {
    let styleElement = document.getElementById('fullscreen_styles_js');

    if (!styleElement) {
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.id = 'fullscreen_styles_js';
        document.getElementsByTagName('head')[0].appendChild(styleElement);
    }

    styleElement.appendChild(document.createTextNode(newStyle));
}

const styleText = `
.fullScreenFixedFit {
    transform: translateY(${TOP_NAV_HEIGHT}px);
}
.fullScreenHeight {
    height: calc(100vh - ${TOP_NAV_HEIGHT}px) !important;
}
.fullScreenMinHeight {
    min-height: calc(100vh - ${TOP_NAV_HEIGHT}px) !important;
}
.wptd-modal-wrap.wptd-modal-fullScreen .wptd-modal-core-content { height: calc(100% - ${TOP_NAV_HEIGHT}px) !important;}
.wptd-modal-wrap.animation-type-rr {
    height: calc(100% - ${TOP_NAV_HEIGHT}px) !important;
    margin-top: ${TOP_NAV_HEIGHT}px !important;
}
`;

if (shouldRenderNavigation()) {
    addNewStyle(styleText);
}

let isEnableBounce = true;
@showHide
export default class Navigation extends React.PureComponent {
    currentStatusBarTheme = null;

    constructor(props) {
        super(props);
        let theme;
        const pageConfig = props.PageComp.pageConfig || {};
        let navigationTheme = pageConfig.navigation ? pageConfig.navigation : 'default';

        if (navigationTheme.dynamic && typeof navigationTheme.getNavigation === 'function') {
            navigationTheme = navigationTheme.getNavigation().navigation;
        }

        if (typeof navigationTheme === 'string') {
            theme = themeConfig[navigationTheme] || themeConfig.default;
        } else if (typeof navigationTheme === 'object') {
            theme = { ...themeConfig.default, ...navigationTheme };
        }

        if (pageConfig.extendNavigationTheme && typeof pageConfig.extendNavigationTheme === 'object') {
            theme = { ...theme, ...pageConfig.extendNavigationTheme };
        }

        this.initialTheme = { ...theme };
        this.navigationTheme = navigationTheme;
        const { forbidBounce = true } = pageConfig;
        this.forbidBounce = forbidBounce || navigationTheme === 'scroll';

        const { state = {} } = window.history.state || {};
        this.state = {
            title: '',
            index: state.index || 0,
            theme,
        };

        this.nativeChangeStatusBar(this.state.theme);
        if (navigationTheme === 'scroll') {
            this.listenScroll();
        }

        if (this.forbidBounce) {
            setTimeout(() => {
                this.disableBounce();
            });
        }
    }

    componentDidMount() {
        const { index } = this.state;
        this.id = `page-head-${index}`;
        this.bindSetTitle();
    }

    componentDidUpdate() {
        // 仅做leftbtn rightbtn 更新操作
        const { props } = this;
        const pageConfig = props.PageComp.pageConfig || {};
        let navigationTheme = pageConfig.navigation ? pageConfig.navigation : 'default';
        let isEdit = false;
        if (typeof navigationTheme === 'object') {
            const updateState = {};
            const { theme } = this.state;
            if (theme.leftBtn !== navigationTheme.leftBtn) {
                updateState.leftBtn = navigationTheme.leftBtn;
                isEdit = true;
            }
            if (theme.rightBtn !== navigationTheme.rightBtn) {
                updateState.rightBtn = navigationTheme.rightBtn;
                isEdit = true;
            }
            if (isEdit) {
                this.setState({
                    theme: Object.assign({}, theme, updateState),
                });
            }
        }
    }

    componentWillUnmount() {
        $(document).off('setTitleInNavigation');
        if (this.navigationTheme === 'scroll') {
            this.removeScroll();
        }
    }

    onPageShow = () => {
        this.nativeChangeStatusBar(this.initialTheme, true);
        this.navigationTheme === 'scroll' && this.listenScroll();
        this.forbidBounce && this.disableBounce();
    };

    onPageHide = () => {
        if (this.navigationTheme === 'scroll' || this.forbidBounce) {
            this.navigationTheme === 'scroll' && this.removeScroll();
            this.forbidBounce && this.enableBounce();
        }
    };

    listenScroll = () => {
        $(window).on('scroll', this.scrollCallBack);
    };

    removeScroll = () => {
        $(window).off('scroll', this.scrollCallBack);
    };

    disableBounce = () => {
        // 禁用弹性手势
        if (isEnableBounce) {
            WPT.wptBridge.wptBounceEnable({
                enable: 'no',
            });
            isEnableBounce = false;
        }
    };

    enableBounce = () => {
        // 恢复弹性手势
        if (!isEnableBounce) {
            WPT.wptBridge.wptBounceEnable({
                enable: 'yes',
            });
            isEnableBounce = true;
        }
    };

    scrollCallBack = () => {
        if (window.scrollY > 10) {
            this.setForceTheme({
                ...this.initialTheme,
                backgroundColor: '#FFFFFF',
                textColor: '#333',
                operationIconTheme: 'dark',
                statusBarTheme: 'dark',
            });
        }

        if (window.scrollY <= 10) {
            this.setForceTheme({
                ...this.initialTheme,
            });
        }

        if (window.scrollY <= 100) {
            this.setState({
                scrollOpacity: window.scrollY <= 0 ? 1 : window.scrollY / 80,
            });
        } else {
            this.setState({
                scrollOpacity: 1,
            });
        }
    };

    setForceTheme = (theme) => {
        this.forceStatusBarTheme = theme;
        this.nativeChangeStatusBar();
        this.setState({
            theme,
        });
    };

    bindSetTitle = () => {
        $(document).on('setTitleInNavigation', (e, title) => {
            const { state = {} } = window.history.state || {};
            if (this.id === `page-head-${state.index || 0}`) {
                this.setState({
                    title,
                });
            }
        });
    };

    nativeChangeStatusBar = (theme, isOnShow = false) => {
        if (this.forceStatusBarTheme) theme = this.forceStatusBarTheme;
        if (this.currentStatusBarTheme === isBlack[theme.statusBarTheme] && !isOnShow) return;
        this.currentStatusBarTheme = isBlack[theme.statusBarTheme];
        WPT.wptBridge.changeStatusBarTheme({
            isBlack: isBlack[theme.statusBarTheme],
        });
    };

    handleBack = () => {
        let backFlag = false;
        const pageBackList = WPT.$curPage[0]?.showHideList?.filter((item) => typeof item.onPageBack === 'function');
        if (pageBackList?.length) {
            pageBackList.forEach((item) => {
                backFlag = backFlag | item.onPageBack(back);
            });
            backFlag && back();
            return;
        }

        back();
    };

    handleClose = () => {
        let closeFlag = false;
        const pageCloseList = WPT.$curPage[0].showHideList?.filter((item) => typeof item.onPageClose === 'function');
        if (pageCloseList?.length) {
            pageCloseList.forEach((item) => {
                closeFlag = closeFlag | item.onPageClose(close);
            });

            closeFlag && close();
            return;
        }

        close();
    };

    more = () => {
        WPT.wptBridge.wptCheckShare();
    };

    _renderRightBtn = () => {
        const { theme } = this.state;
        if (!theme.rightBtnShow) return null;
        if (theme.rightBtn) {
            return <div className={S.rightBtn}>{theme.rightBtn}</div>;
        }

        return (
            <div
                className={cx(
                    S.rightBtn,
                    theme.rightBtnTheme === 'share' ? S.share : S.more,
                    S[theme.operationIconTheme]
                )}
                {...onTap(this.more)}
            />
        );
    };

    _renderLeftBtn = () => {
        const { theme } = this.state;
        if (!theme.leftBtnShow) return null;
        if (theme.leftBtn) {
            return <div className={S.customLeftBtn}>{theme.leftBtn}</div>;
        }
        // 左侧不支持 share 与 more
        return null;
    };

    render() {
        const { index, theme, title, scrollOpacity = 1 } = this.state;
        const noTopheight = {
            height: 0,
        };
        return (
            theme.needNavigation && (
                <div
                    className={S.navigationWrapper}
                    style={this.navigationTheme !== 'scroll' ? { paddingTop: `${TOP_NAV_HEIGHT - 44}px` } : noTopheight}
                >
                    <div
                        className={S.navigationBox}
                        style={{ color: theme.textColor, paddingTop: `${TOP_NAV_HEIGHT - 44}px` }}
                    >
                        {theme.customNavigation ? (
                            theme.customNavigation
                        ) : (
                            <>
                                <div
                                    className={cx(
                                        S.navigationBackgroundBox,
                                        os.android && theme.backgroundColor !== '#FFFFFF' && S.androidFix
                                    )}
                                    style={{ backgroundColor: theme.backgroundColor, opacity: scrollOpacity }}
                                />
                                <div className={cx(S.contentWrapper, index > 3 && theme.closeBtnShow && S.showClose)}>
                                    <div
                                        className={cx(S.leftBtn, S[theme.operationIconTheme])}
                                        {...onTap(this.handleBack)}
                                    />
                                    {this._renderLeftBtn()}
                                    <div
                                        className={cx(S.closeBtn, S[theme.operationIconTheme])}
                                        {...onTap(this.handleClose)}
                                    />
                                    <div className={S.titleText}>{theme.customTitle || title || '微拍堂'}</div>
                                    {this._renderRightBtn()}
                                </div>
                            </>
                        )}
                        {theme.operationIconTheme === 'dark' && (
                            <div className={S.bottomBorder} style={{ opacity: scrollOpacity }} />
                        )}
                    </div>
                </div>
            )
        );
    }
}
